package com.itheima.tlias84.controller;

import com.itheima.tlias84.annotation.Log;
import com.itheima.tlias84.dto.SelectClazzAllDTO;
import com.itheima.tlias84.dto.SelectClazzDetailDTO;
import com.itheima.tlias84.po.InsertClazzParam;
import com.itheima.tlias84.po.SelectClazzPageParam;
import com.itheima.tlias84.po.UpdateClazzParam;
import com.itheima.tlias84.service.ClazzService;
import com.itheima.tlias84.utils.ResultUtil;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 班级控制器
 */
@RestController
@RequestMapping("/clazzs")
public class ClazzController {
    @Resource
    ClazzService service;

    /**
     * 添加班级
     *
     * @param param 班级参数
     * @return 添加结果
     */
    @Log
    @PostMapping
    public ResultUtil insertClazz(@Validated @RequestBody InsertClazzParam param) {
        int inserted = service.insertClazz(param);
        return inserted == 0 ? ResultUtil.fail("添加失败") : ResultUtil.success("添加成功");
    }

    /**
     * 分页查询班级
     *
     * @return 分页查询结果
     */
    @GetMapping
    public ResultUtil selectClazzByPage(SelectClazzPageParam param) {
        //判空
        if (Objects.isNull(param.getPage()) || Objects.isNull(param.getPageSize())) {
            return ResultUtil.fail("分页参数不存在");
        }
        return service.selectClazzByPage(param);
    }

    /**
     * 修改更新班级
     *
     * @param param 班级参数
     * @return 修改数据
     */
    @Log
    @PutMapping
    public ResultUtil updateClazz(@RequestBody UpdateClazzParam param) {
        int updated = service.updateClazz(param);
        return updated == 0 ? ResultUtil.fail("修改失败") : ResultUtil.success("修改成功");
    }

    /**
     * 根据id查询班级
     *
     * @param id 班级id
     * @return 查询结果
     */
    @GetMapping("/{id}")
    public ResultUtil selectClazzById(@PathVariable("id") Integer id) {
        SelectClazzDetailDTO dto = service.selectClazzById(id);
        return ResultUtil.success(dto);
    }

    /**
     * 查询所有班级
     * @return 查询结果
     */
    @GetMapping("list")
    public ResultUtil selectClazzAll() {
        List<SelectClazzAllDTO> dtos = service.selectClazzAll();
        return ResultUtil.success(dtos);
    }

    /**
     * TODO 判断是否有学生：根据id删除班级
     * @param id 班级id
     * @return 返回结果
     */
    @Log
    @DeleteMapping("/{id}")
    public ResultUtil deleteClazzById(@PathVariable("id") Integer id) {
        //服务层：判断是否有学生
        int deleted = service.deleteById(id);
        return deleted == 0 ? ResultUtil.fail("删除失败") : ResultUtil.success("删除成功");
    }

}
